/**
 * Project Name:kany-utils
 * File Name:KeyStoreUtil.java
 * Package Name:me.kany.utils.httpclient.httpclient
 * Date:2016年2月24日上午10:49:00
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 *
*/

package me.kany.utils.httpclient;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:KeyStoreUtil <br/>
 * Function: Https的证书管理工具. <br/>
 * Date:     2016年2月24日 上午10:49:00 <br/>
 * @author   Jason.Wang
 * @version  
 * @since    JDK 1.7
 * @see 	 
 */
public class KeyStoreUtil {
    private static Map<String, KeyStoreMaterial> keystores = new HashMap<String, KeyStoreMaterial>();
    private static final Object lock = new Object();
    
    /**
     * 
     * getKeyStore:获取安全连接的证书. <br/>
     *
     * @author Jason.Wang
     * @param path
     * @param password
     * @return
     * @since JDK 1.7
     */
    public static KeyStoreMaterial getKeyStore(String path, String password) {
        String key = formatKey(new String[] { path, password });
        KeyStoreMaterial result = keystores.get(key);
        if (result == null) {
            synchronized (lock) {
                result = keystores.get(key);
                if (result == null) {
                    try {
                        KeyStore keyStore = loadItemTokeyStore(path, password);
                        result = new KeyStoreMaterial(password, keyStore);
                        keystores.put(key, result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }
    
    /**
     * 
     * formatKey:生存Key. <br/>
     *
     * @author Jason.Wang
     * @param strs
     * @return
     * @since JDK 1.7
     */
    private static String formatKey(String[] strs) {
        StringBuffer sb = new StringBuffer();
        for (String str : strs) {
            sb.append(str).append("#");
        }
        return sb.toString();
    }
    
    /**
     * 
     * loadItemTokeyStore:加载证书文件. <br/>
     *
     * @author Jason.Wang
     * @param path
     * @param password
     * @return
     * @throws Exception
     * @since JDK 1.7
     */
    private static KeyStore loadItemTokeyStore(String path, String password) throws Exception {
        // BufferedInputStream fileInput = null;
        KeyStore keyStore = null;
        InputStream fileInput = null;
        if (path.startsWith("classpath:")) {
            path = path.substring("classpath:".length());
            // fileInput = new BufferedInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
            fileInput = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        } else if (path.startsWith("file:")) {
            path = path.substring("file:".length());
            fileInput = new BufferedInputStream(new FileInputStream(path));
        }
        if(fileInput!=null){
            try {
                keyStore = KeyStore.getInstance("PKCS12");
                keyStore.load(fileInput, password.toCharArray());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                fileInput.close();
            }
        }
        
        return keyStore;
    }
}
